
import React, { useEffect } from "react"
import { useNavigate, useRoutes, useLocation } from "react-router-dom"
//类型
type Iguard = (key: string, routes: Iroutes, storage?: string) => React.ReactNode

type route = {
    path: string,
    element?: React.ReactNode
}

type Iroute = route & {
    children?: Array<route>
}

export type Iroutes = Array<Iroute>

//重载window类型
declare global {
    interface Window {
        [k: string]: any
    }
}


const useRoutesWithGuard: Iguard = (key, routes, storage = 'sessionStorage') => {

    // let token: string | null = sessionStorage.getItem(key);

    let token: string | null = window[storage].getItem(key);

    let navigate = useNavigate()

    let Element = useRoutes(routes)

    let location = useLocation()

    useEffect(() => {
        if (!token) {
            //没有token,跳转到login
            //如果访问的页面不是login 就跳转到login
            if (location.pathname !== "/login") {
                navigate('/login')
            }
        }
    })

    return Element
}

export default useRoutesWithGuard